<?php

namespace App\Server\Task;

use PHPMailer\PHPMailer\PHPMailer;
use Exception;

class SendEmailTask extends AbstractTask {
	
	/**
	 * 执行任务的内容
	 *
	 * @param mixed $taskData
	 *        	任务数据
	 * @param int $taskId
	 *        	执行任务的task编号
	 * @param int $fromWorkerId
	 *        	派发任务的worker进程号
	 * @author : evalor <master@evalor.cn>
	 */
	function run($taskData, $taskId, $fromWorkerId) {
		$email = $taskData['email'];
		$content = $taskData['content'];
		$title = $taskData['title'];
		// 需要注意的是task编号并不是绝对唯一
		// 每个worker进程的编号都是从0开始
		// 所以 $fromWorkerId + $taskId 才是绝度唯一的编号
		// !!! 任务完成需要 return 结果
		$mail = new PHPMailer ( true ); // Passing `true` enables exceptions
		try {
			// Server settings
			$mail->SMTPDebug = 2; // Enable verbose debug output
			$mail->isSMTP (); // Set mailer to use SMTP
			$mail->Host = 'smtp.qq.com'; // Specify main and backup SMTP servers
			$mail->SMTPAuth = true; // Enable SMTP authentication
			$mail->Username = '327907762@qq.com'; // SMTP username
			$mail->Password = 'rqzkjdskhhxlcbeh'; // SMTP password
			$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
			$mail->Port = 465; // TCP port to connect to
			                   
			// Recipients
			$mail->setFrom ( '327907762@qq.com', 'Mailer' );
			// Add a recipient
			$mail->addAddress ( $email, 'Joe User' );
			
			// $mail->addAddress ( 'ellen@example.com' ); // Name is optional
			// $mail->addReplyTo ( 'info@example.com', 'Information' );
			// $mail->addCC ( 'cc@example.com' );
			// $mail->addBCC ( 'bcc@example.com' );
			
			// Attachments
			// $mail->addAttachment ( '/var/tmp/file.tar.gz' ); // Add attachments
			// $mail->addAttachment ( '/tmp/image.jpg', 'new.jpg' ); // Optional name
			
			// Content
			// Set email format to HTML
			$mail->isHTML ( true );
			$mail->Subject = $title;
			$mail->Body = $content;
			$mail->Charset='UTF-8';
			// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
			
			$mail->send ();
			
			echo 'Message has been sent';
		} catch ( Exception $e ) {
			echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
		}
		
		return $taskId . $fromWorkerId;
	}
	
	/**
	 * 任务执行完的回调
	 *
	 * @param mixed $result
	 *        	任务执行完成返回的结果
	 * @param int $task_id
	 *        	执行任务的task编号
	 * @author : evalor <master@evalor.cn>
	 */
	function finish($result, $task_id) {
		// 任务执行完的处理
		echo "finish :" . $result . PHP_EOL;
	}
}